<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="项目名称" class="filter-item" style="width: 200px" />
      <el-select v-model="listQuery.type" placeholder="项目类型" clearable style="width: 240px" class="filter-item">
        <el-option v-for="(index, item) in typeOptions" :key="index" :label="index" :value="item" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate"> 新增</el-button>
    </div>
    <!-- 数据 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column v-if="false" label="ID" prop="id" aligin="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" prop="name">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false" @click="handleUpdate(scope.row.id)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="项目类型" prop="type">
        <template slot-scope="scope">
          <span>{{ typeOptions[scope.row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="add_time">
        <template slot-scope="scope">
          <span>{{ changeDate(scope.row.add_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" prop="edit_time">
        <template slot-scope="scope">
          <span>{{ changeDate(scope.row.edit_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(id)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 新增/编辑dialog -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="temp.name" type="text" maxlength="30" minlength="3" show-word-limit="" />
        </el-form-item>
        <el-form-item label="项目类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择">
            <el-option v-for="(index, item) in typeOptions" :key="index" :label="index" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getProjectList, createProject, updateProject, deleteProject, getProject } from '@/api/project'
import { dateFormat } from '@/utils/data'
export default {
  name: 'Project',
  components: { Pagination },
  data() {
    return {
      list: [],
      total: 0,
      listQuery: {
        name: '',
        type: 'all',
        page: 1,
        limit: 20
      },
      typeOptions: {
        all: '全部',
        web: 'Web自动化',
        app: 'App自动化',
        interface: '接口自动化'
      },
      listLoading: false,
      dialogFormVisible: false,
      temp: {
        id: undefined,
        name: '',
        type: 'web',
        remark: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        name: [
          { required: true, message: '项目名称不能为空', trigger: 'change' },
          { min: 3, max: 20, message: '名称长度限制为3-20', trigger: 'blur' }
        ]

      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.listQuery.type === 'all') {
        delete this.listQuery.type
      }
      getProjectList(this.listQuery).then((res) => {
        this.list = res.results
        console.log('list:', this.list)
        this.total = res.count
        this.listLoading = false
      })
    },
    changeDate: function(attr) {
      return dateFormat(attr)
    },
    handleFilter() {
      console.log('goto search')
      this.total = 0
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        type: 'web',
        remark: ''
      }
    },
    handleCreate() {
      console.log('go to create!')
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(id) {
      getProject(id).then(response => {
        this.temp = response.data
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createProject(this.temp).then(() => {
            this.getList()
            this.dialogFormVisible = false
            this.$notify({
              title: 'success',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        const tempDate = Object.assign({}, this.temp)
        updateProject(tempDate.id, tempDate).then(() => {
          this.getList()
          this.dialogFormVisible = false
          this.$notify({
            title: 'success',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    handleDelete(row) {
      this.$confirm('确认要删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then((action) => {
        if (action === 'confirm') {
          deleteProject(row.id).then((res) => {
            if (res) {
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
              this.$message({
                type: 'success',
                message: '删除成功'
              })
            }
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
